﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;
using Apmis2._1.Hubs;
using Microsoft.AspNet.SignalR;

namespace Apmis2._1.Controllers
{
    public class FileUploadController : ApiController
    {

        [HttpPost]
        [Route("api/patient/{patientID:guid}/document")]
      public async Task<IHttpActionResult> Post()
        {
            // Would need to add certain parameters from file and save data into database
            // explore creating a class model for the data+repo with save and get
            // see utility:http://technet.microsoft.com/en-us/library/ff929144.aspx
            // increase max upload size with this parameter in web config.
            //<system.web>
                //...
                //<httpRuntime targetFramework="4.5" maxRequestLength="104857600" />
                //...
                //</system.web>
            
            if (!Request.Content.IsMimeMultipartContent())
            {
                
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
          
          try
            {
                var uploadpath = HttpContext.Current.Server.MapPath("~/App_Data/"); // + "UploadFolder") ("~/uploaded");
               
                var provider = new WithExtensionMultipartFormDataStreamProvider(uploadpath);
                await Request.Content.ReadAsMultipartAsync(provider);

               // Show all the key-value pairs.
               // foreach (var key in provider.FormData.AllKeys)
               // {
               //     foreach (var val in provider.FormData.GetValues(key))
               //     {
               //         Trace.WriteLine(string.Format("{0}: {1}", key, val));
               //     }
               // }



                var mess = "";
                 string sender = "file upload";
              
              List<string> messages = new List<string>();
                foreach (var file in provider.FileData)
                {
                  IHubContext context =  GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
                    FileInfo fi = new FileInfo(file.LocalFileName);
                    messages.Add("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)" );
                    mess = ("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)");
                    context.Clients.All.broadcastMessage(sender, mess);               //Send("simpa","simpa");
                    
                }
               
                
                return Ok(messages);
            }
            catch (Exception ex)
            {

                return BadRequest("invalid request");
            }

        }

    }
}
